#!/usr/bin/env python

import sys

import django
from django.template import loader

from apps.goods import models
from apps.goods.models import SKU
from shopping_mall import settings
from utils.goods import get_categories, get_breadcrumb, get_goods_specs

sys.path.insert(0, '../')

# 加载Django黄金
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo.settings')

django.setup()

def generate_static_sku_detail_html(sku_id):
    # 查询相关数据
    """提供商品详情页"""
    # 获取当前sku的信息
    sku = SKU.objects.get(id=sku_id)
    # 查询商品频道分类
    categories = get_categories()
    # 查询面包屑导航
    breadcrumb = get_breadcrumb(sku.category)
    # 获取规格
    specs = get_goods_specs(sku)

    # 渲染页面
    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
        'specs': specs,
    }
    # 加载需要渲染的模板
    # 获取模板对象
    index_template = loader.get_template('detail.html')
    # 把数据渲染到模板上
    index_html_data = index_template.render(context)
    # 把渲染好的模板保存成HTML文件写入指定文件
    file_path = os.path.join(os.path.dirname(settings.BASE_DIR),
                             'front_end_pc/goods/' + str(sku_id) + '.html')

    with open(file_path, 'w') as f:
        f.write(index_html_data)

if __name__ == '__main__':
    skus = models.SKU.objects.all()
    for sku in skus:
        print(sku.id)
        generate_static_sku_detail_html(sku.id)